package com.icoolkj.learn.juc.future;

import com.icoolkj.learn.juc.base.utils.SleepTools;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/03/05 13:52
 */
@Slf4j
public class FutureTaskDemo2 {
    public static void main(String[] args) {
        FutureTask<String> ft1 = new FutureTask<String>(new T1Task());
        FutureTask<String> ft2 = new FutureTask<String>(new T2Task());
        FutureTask<String> ft3 = new FutureTask<String>(new T3Task());
        FutureTask<String> ft4 = new FutureTask<String>(new T4Task());
        FutureTask<String> ft5 = new FutureTask<String>(new T5Task());

        // 构建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        executorService.submit(ft1);
        executorService.submit(ft2);
        executorService.submit(ft3);
        executorService.submit(ft4);
        executorService.submit(ft5);

        //获取执行结果
        try {
            log.info("任务1：{}", ft1.get());
            log.info("任务2：{}", ft2.get());
            log.info("任务3：{}", ft3.get());
            log.info("任务4：{}", ft4.get());
            log.info("任务5：{}", ft5.get());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

        executorService.shutdown();
    }

    static class T1Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            log.info("T1: 查询商品基本信息...");
            SleepTools.second(1);
            return "T1，商品基本信息查询成功";
        }
    }

    static class T2Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            log.info("T2: 查询商品价格信息...");
            SleepTools.second(1);
            return "T2，商品价格信息查询成功";
        }
    }

    static class T3Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            log.info("T3: 查询商品库存信息...");
            SleepTools.second(5);
            return "T3，商品库存信息查询成功";
        }
    }

    static class T4Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            log.info("T4: 查询商品图片信息...");
            SleepTools.milliseconds(500);
            return "T4，商品图片信息查询成功";
        }
    }

    static class T5Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            log.info("T5: 查询商品销售信息...");
            SleepTools.milliseconds(500);
            return "T5，商品销售信息查询成功";
        }
    }

}
